package com.zl.tby.service.impl;

import com.zl.tby.core.base.bean.TbyPageResult;
import com.zl.tby.core.base.util.ToolsUtil;
import com.zl.tby.core.common.R;
import com.zl.tby.dto.TbyUavInfoQuery;
import com.zl.tby.model.TbyUavInfo;
import com.zl.tby.repository.TbyUavInfoRepo;
import com.zl.tby.service.ITbyUavInfoService;
import com.zl.tby.vo.TbyUavInfoForm;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.data.annotation.Tran;
import org.noear.wood.DataItem;
import org.noear.wood.DbContext;
import org.noear.wood.IPage;
import org.noear.wood.annotation.Db;
import org.noear.wood.utils.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * 无人机信息 接口实现类
 * @author changpeng
 * @version 1.0
 * @since 2024/8/6 20:22
 */
@Slf4j
@Component
public class TbyUavInfoServiceImpl implements ITbyUavInfoService {

    @Db
    private TbyUavInfoRepo tbyUavInfoRepo;
    @Db
    private DbContext db;

    @Override
    @Tran
    public R<TbyUavInfo> add(TbyUavInfoForm form) {
        TbyUavInfo entity = form.createEntity();
        entity.setCreateBy(ToolsUtil.getLoginUserId());
        entity.setCreateTime(LocalDateTime.now());
        long id = tbyUavInfoRepo.insert(entity, true);
        entity.setId(id);
        return R.ok(entity);
    }

    @Override
    @Tran
    public R<TbyUavInfo> update(TbyUavInfoForm form) {
        TbyUavInfo entity = this.get(form.getId());
        if (entity == null) {
            return R.failed("数据不存在");
        }
        form.updateEntity(entity);
        entity.setUpdateBy(ToolsUtil.getLoginUserId());
        entity.setUpdateTime(LocalDateTime.now());
        tbyUavInfoRepo.updateById(entity, false);
        return R.ok(entity);
    }

    @Override
    public R<TbyUavInfo> updateData(TbyUavInfoForm form) {
        TbyUavInfo entity = this.get(form.getId());
        if (entity == null) {
            return R.failed("数据不存在");
        }
        form.updateData(entity);
        entity.setUpdateBy(ToolsUtil.getLoginUserId());
        entity.setUpdateTime(LocalDateTime.now());
        tbyUavInfoRepo.updateById(entity, false);
        return R.ok(entity);
    }

    @Override
    public int delete(Long id) {
        return tbyUavInfoRepo.deleteById(id);
    }

    @Override
    public TbyUavInfo get(Long id) {
        return tbyUavInfoRepo.selectById(id);
    }

    @Override
    public TbyPageResult<TbyUavInfo> page(TbyUavInfoQuery query) {
        IPage<TbyUavInfo> iPage = tbyUavInfoRepo.selectPage(query.getOffset(), query.getSize(), mp -> {
            mp.whereTrue()
                    .andIf(StringUtils.isNotEmpty(query.getName()), "name like ?", "%" + query.getName() + "%")
                    .andIf(StringUtils.isNotEmpty(query.getModel()), "model like ?", "%" + query.getModel() + "%")
                    .andIf(StringUtils.isNotEmpty(query.getCode()), "code = ?", "%" + query.getCode() + "%");
            if (StringUtils.isNotEmpty(query.getOrder())) {
                mp.orderBy(query.getOrder());
            }
        });
        return new TbyPageResult(iPage, query);
    }

    @Override
    public List<TbyUavInfo> list(TbyUavInfoQuery query) {
        List<TbyUavInfo> dataList = tbyUavInfoRepo.selectList(mapperWhereQ -> {
            mapperWhereQ.whereTrue().andIf(StringUtils.isNotEmpty(query.getName()), "name like ?", "%" + query.getName() + "%")
                    .andIf(StringUtils.isNotEmpty(query.getModel()), "model like ?", "%" + query.getModel() + "%")
                    .andIf(StringUtils.isNotEmpty(query.getCode()), "code = ?", "%" + query.getCode() + "%");
            if (StringUtils.isNotEmpty(query.getOrder())) {
                mapperWhereQ.orderBy(query.getOrder());
            }
        });
        for (TbyUavInfo entity : dataList) {
            entity.setFlightTime(ToolsUtil.divide(entity.getFlightTime(), new BigDecimal(3600), 1));
        }
        return dataList;
    }

    @Override
    public R<Boolean> checkCode(Long id, String code) {
        if (StringUtils.isEmpty(code)) {
            return R.ok(false);
        }
        List<TbyUavInfo> dbList = this.tbyUavInfoRepo.selectList(mp -> {
            mp.whereEq("code", code);
        });
        for (TbyUavInfo data : dbList) {
            if (id == null && data.getCode().equals(code)) {
                return R.ok(true);
            } else if (id != null && data.getCode().equals(code) && id.compareTo(data.getId()) != 0) {
                return R.ok(true);
            }
        }
        return R.ok(false);
    }

    @Override
    public R<Boolean> checkDeviceId(Long id, String deviceId) {
        if (StringUtils.isEmpty(deviceId)) {
            return R.ok(false);
        }
        List<TbyUavInfo> dbList = this.tbyUavInfoRepo.selectList(mp -> {
            mp.whereEq("device_id", deviceId);
        });
        for (TbyUavInfo data : dbList) {
            if (id == null && data.getDeviceId().equals(deviceId)) {
                return R.ok(true);
            } else if (id != null && data.getDeviceId().equals(deviceId) && id.compareTo(data.getId()) != 0) {
                return R.ok(true);
            }
        }
        return R.ok(false);
    }

    @Override
    @Tran
    public void updateLonlat(String code, String longitude, String latitude) {
        if (StringUtils.isNotEmpty(longitude) && StringUtils.isNotEmpty(latitude)) {
            DataItem data = new DataItem();
            data.set("lon_lat", longitude + "," + latitude);
            data.set("status", 1);
            try {
                db.table("tby_uav_info").whereEq("device_id", code).update(data);
            } catch (Exception ex) {
                log.error("更新无人机坐标异常", ex);
            }
        } else {
            updateOnLine(code);
        }
    }

    @Override
    public void updateOffLine(Long id) {
        TbyUavInfo entity = new TbyUavInfo();
        entity.setId(id);
        entity.setStatus(0);
        this.tbyUavInfoRepo.updateById(entity, true);
    }



    @Override
    @Tran
    public void updateOnLine(String code) {
        DataItem data = new DataItem();
        data.set("status", 1);
        try {
            db.table("tby_uav_info").whereEq("device_id", code).update(data);
        } catch (Exception ex) {
            log.error("更新无人机坐标异常", ex);
        }
    }

    /**
     * 根据设备id获取设备信息
     * @author AnWeiNan
     * @date 2024/11/5 下午6:40
     */
    @Override
    public List<TbyUavInfo> selectByDeviceId(String deviceId) {
        // 查询设备ID相关的记录
        List<TbyUavInfo> dbList = this.tbyUavInfoRepo.selectList(mp -> {
            mp.whereEq("device_id", deviceId);
        });

        // 如果查询到的结果为空，返回一个空列表；否则返回查询结果
        return dbList.isEmpty() ? Collections.emptyList() : dbList;
    }

    /**
     * 根据设备id修改无人机信息
     * @author AnWeiNan
     * @date 2024/11/5 下午6:52
     */
    @Override
    @Tran
    public void updateByDeviceId(Long id, BigDecimal flightDistance, BigDecimal flightTime, Long flightCount) {
        if (id != null && flightDistance != null && flightTime != null && flightCount != null) {
            DataItem data = new DataItem();
            data.set("flight_distance", flightDistance);
            data.set("flight_time", flightTime);
            data.set("flight_count", flightCount);
            try {
                db.table("tby_uav_info").whereEq("id", id).update(data);
            } catch (Exception ex) {
                log.error("更新无人机信息异常", ex);
            }
        }
    }
}
